package cn.lyq.card.ui.device

import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.src.Status
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.act_device_list.*


class DeviceListActivity : BaseActivity() {

    private val mModel by lazy {
        getVM(DeviceVM::class.java)
    }
    private val mAdapter by lazy {
        DeviceAdapter()
    }

    override fun getLayoutId(): Int {
        return R.layout.act_device_list
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.str_device_bug)

        rvDevice.layoutManager = LinearLayoutManager(this)
        rvDevice.adapter = mAdapter
    }

    override fun isLightBarColor(): Boolean {
        return true
    }

    override fun initListener() {
        super.initListener()
        refreshDevice.setOnRefreshListener {
            getData()
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            DeviceDetailActivity.start(this, mAdapter.data[position])
        }
        mAdapter.addChildClickViewIds(R.id.tvBuyDevice)
        mAdapter.setOnItemChildClickListener { _, _, position ->
            DeviceDetailActivity.start(this, mAdapter.data[position])
        }
    }

    override fun initObserver() {
        super.initObserver()
        getData()
    }

    private fun getData() {
        mModel.getList().observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> {
                    if (!refreshDevice.isRefreshing) {
                        refreshDevice.isRefreshing = true
                    }
                }
                Status.SUCCESS -> {
                    mAdapter.setList(it.requireData())
                    refreshDevice.isRefreshing = false
                }
                Status.ERROR -> {
                    ToastUtils.showShort(it.message.getMsg())
                    refreshDevice.isRefreshing = false
                }
            }
        })

    }
}